from smap.driver import SmapDriver
from smap.util import periodicSequentialCall
import calendar
from dateutil import tz
from datetime import datetime
import os

class wspfkBmsDriver(SmapDriver):
	
	def setup(self, opts):
		folder = '/home/cbe/BSG_share/bsg on 169.229.130.74/!Projects/IEQ/Monitoring/WSPFK - 2012/Data/Trends/5th Floor UFTs/new data/'
		self.ids = {}
		self.data = {}
		for filename in os.listdir(folder):
			boxname = filename[:5]
			pointname = os.path.splitext(filename[5:])[0]
			smapname = boxname + '/' + pointname
			ts = self.add_timeseries('/%s' % smapname, 'NA', data_type="double")
			self.ids[smapname] = ts['uuid']
			f = open(folder + filename, 'rb')
			self.data[smapname] = f.readlines()[2:]
			f.close()		
		self.period = opts.get("Period", 1000000)

	def start(self):
		periodicSequentialCall(self.read).start(self.period)
	
	def read(self):
		time_zone = tz.gettz('America/Los_Angeles')
		errorCount = 0
		for smapname in self.data:
			for row in self.data[smapname]:
				line = row.split(',')
				try:
					point_date = datetime.strptime(line[0][:19], '%Y-%m-%dT%H:%M:%S').replace(tzinfo = time_zone)
					smaptime = calendar.timegm(point_date.utctimetuple())
				except:
					continue
				try:
					self.add(self.ids[smapname], smaptime, float(line[1]))
				except ValueError:
					errorCount += 1
		print errorCount
